// 2、无头双向链表实现
public class LinkedList {

    static class ListNode{
        private int val;
        private ListNode prev;
        private ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;
    //头插法
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        head.prev = node;
        node.next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        ListNode cur = head;
        while(cur != null){
            cur = cur.next;
        }
        cur.next = node;
        node.prev = cur;
    }

    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index, int data) {
        if(index < 0 || index > size()){
            throw new IndexOutOfException("下标位置不合法");
        }
        ListNode node = new ListNode(data);
        if(head == null){
            head = node;
        }
        ListNode cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        node.next = cur.next;
        cur.next.prev = node;
        node.prev = cur;
        cur.next = node;
    }

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        ListNode cur = head;
        while(cur != null){
            if(cur.val == key){
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    //删除第一次出现关键字为key的节点
    public void remove(int key) {
        ListNode cur = head;
        int len = 0;
        while(cur != null){
            if(cur.val == key){
                cur.next = cur.next.next;
                cur.next.next.prev = cur;
                break;
            }
            cur = cur.next;
            len++;
        }
        if(len == size()){
            System.out.println("没有找到值为"+key+"的结点");
        }
    }

    //删除所有值为key的节点
    public void removeAllKey(int key) {
        ListNode cur = head;
        int len = 0;
        while(cur != null){
            if(cur.val == key){
                cur.next = cur.next.next;
                cur.next.next.prev = cur;
            }
            cur = cur.next;
            len++;
        }
        if(len == size()){
            System.out.println("没有找到值为"+key+"的结点");
        }
    }

    //得到单链表的长度
    public int size() {
        int len = 0;
        while(head != null){
            head = head.next;
            len++;
        }
        return len;
    }

    public void display() {
        ListNode cur = head;
        while(cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void clear() {
        ListNode cur = head;
        while(cur != null){
            ListNode curNext = cur.next;
            cur.prev = null;
            cur.next = null;
            cur = curNext;
        }
        head = null;
    }
}